home *** CD-ROM | disk | FTP | other *** search
/ CD ROM Paradise Collection 4 / CD ROM Paradise Collection 4 1995 Nov.iso / program / swagn_r.zip / NUMBERS.SWG / 0043_Hex String to LONGINT.pas < prev    next >
Pascal/Delphi Source File  |  1994-02-09  |  2KB  |  77 lines

  1.  
  2. {  You've probably seen a lot of code to convert a number to HEX.
  3.    Here is one that will take a hex String and covert it back to a number
  4.  
  5.    The conversion is back to type LONGINT, so you can covert to WORDS or
  6.    BYTES by simply declaring your whatever varible you want }
  7.  
  8. {$V-}
  9. USES CRT;
  10.  
  11. VAR
  12.     A   : LONGINT;
  13.     B   : WORD;
  14.     C   : BYTE;
  15.     D   : WORD;
  16.  
  17. { ---------------------------------------------------------------------- }
  18.  
  19. FUNCTION HexToLong(S : STRING) : LONGINT;
  20.  
  21.     FUNCTION ANumBin (B : STRING) : LONGINT; Assembler;
  22.     ASM
  23.       LES DI, B
  24.       XOR CH, CH
  25.       MOV CL, ES : [DI]
  26.       ADD DI, CX
  27.       MOV AX, 0
  28.       MOV DX, 0
  29.       MOV BX, 1
  30.       MOV SI, 0
  31.       @LOOP :
  32.         CMP BYTE PTR ES : [DI], '1'
  33.         JNE @NotOne
  34.           ADD AX, BX   {add power to accum}
  35.           ADC DX, SI
  36.         @NotOne :
  37.         SHL SI, 1      {double power}
  38.         SHL BX, 1
  39.         ADC SI, 0
  40.         DEC DI
  41.       LOOP @LOOP
  42.     END;
  43.  
  44. CONST
  45.   HexDigits : ARRAY [0..15] OF CHAR = '0123456789ABCDEF';
  46.   Legal     : SET OF Char = ['$','0'..'9','A'..'F'];
  47.   BinNibbles : ARRAY [0..15] OF ARRAY [0..3] OF CHAR = (
  48.     '0000', '0001', '0010', '0011',
  49.     '0100', '0101', '0110', '0111',
  50.     '1000', '1001', '1010', '1011',
  51.     '1100', '1101', '1110', '1111');
  52.  
  53. VAR I : BYTE;
  54.     O : STRING;
  55.  
  56. BEGIN
  57. O := '';
  58. HexToLong := 0;       { Returns zero if illegal characters found }
  59. IF S = '' THEN EXIT;
  60. FOR I := 1 TO LENGTH(S) DO
  61.     BEGIN
  62.     IF NOT (S[i] in LEGAL) THEN EXIT;
  63.     O := O + binNibbles[PRED(POS(S[i],Hexdigits))];
  64.     END;
  65. HexToLong := ANumBin(O)
  66. END;
  67.  
  68. { ---------------------------------------------------------------------- }
  69.  
  70. BEGIN
  71. ClrScr;
  72. A   := HexToLong('$02F8');
  73. B   := HexToLong('$0DFF');
  74. C   := HexToLong('$00FF');   { The biggest byte there is !! }
  75. D   := HexToLong('');   { this is ILLEGAL !! .. D will be ZERO }
  76. WriteLn(A,' ',B,' ',C,' ',D);
  77. END.